from threading import Thread
import os
#导入模型类
from apps.user import models as user_models
from apps.resource import models as resource_models
from ext import db


class UserModelThread(Thread):
    def __init__(self,data):
        super().__init__()
        self.data = data

    def run(self) -> None:
        '''
        使用这个时，不能使用join等待结束，不然会一直卡住的
        :return:
        '''
        from app import app
        from app import all_lock
        #在激活的app上下文
        with app.app_context():
            try:
                #使用递归锁
                with all_lock:
                    name = self.data.get('name')
                    book = resource_models.BookModel.query.filter_by(name=name).first()
                    if book:
                        print('该数据存在了')
                        return
                    else:
                        print('创建数据')
                        #flask多线程操作数据库时，需要在当前激活的上下文中操作
                        book = resource_models.BookModel(**self.data)
                        db.session.add(book)
                        db.session.commit()
                        return
            except Exception as e:
                db.session.rollback()

#使用多线程的写文件
class WriteFileThread(Thread):
    def __init__(self,file_path,data):
        super().__init__()
        self.file_path = file_path
        self.data = data
    def run(self) -> None:
        if not os.path.exists(self.file_path):
            raise Exception('不存在的文件路径')
        with open(self.file_path,mode='a+',encoding='utf-8') as fp:
            fp.write(self.data+'\n')

